<template>
  <!-- 用户导入对话框 -->
  <n-modal
    v-model:show="props.visible"
    preset="card"
    title="用户导入"
    style="width: 450px"
    @close="emits('close')"
  >
    <div>
      <n-upload
        ref="uploadRef"
        :default-upload="false"
        :file-list="upload.fileList"
        :max="1"
        accept=".xlsx,.xls"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :action="`${upload.url}?updateSupport=${upload.updateSupport}`"
        directory-dnd
        @change="handleChange"
        @before-upload="handleBeforeUpload"
        @finish="handleFileSuccess"
        @progress="handleFileUploadProgress"
      >
        <n-upload-dragger>
          <div style="margin-bottom: 12px">
            <n-icon size="48" :depth="3">
              <UploadFileFilled />
            </n-icon>
          </div>
          <n-text depth="3"> 将文件拖到此处，或<n-text type="primary">点击上传 </n-text></n-text>
        </n-upload-dragger>
      </n-upload>
      <n-space vertical align="center">
        <n-checkbox v-model:checked="upload.updateSupport"> 是否更新已经存在的用户数据 </n-checkbox>
        <n-text depth="3" style="margin-top: 10px">
          仅允许导入“xls”或“xlsx”格式文件！
          <n-button text type="primary" @click="importTemplate">下载模板</n-button>
        </n-text>
      </n-space>
    </div>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" @click="submitFileForm">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="tsx" setup>
import { useDownload } from '@/hooks/useDownload';
import { useUserStore } from '@/stores/user';
import { UploadFileFilled } from '@vicons/material';
import { reactive, ref } from 'vue';
import { NText, useDialog } from 'naive-ui';

const props = defineProps<{ visible: boolean }>();
const emits = defineEmits(['close']);
const uploadRef = ref();
const { download } = useDownload();
const userStore = useUserStore();
const token = userStore.getToken();
const dialog = useDialog();

const upload = reactive({
  open: false,
  url: import.meta.env.VITE_BASE_API + '/user/importData',
  updateSupport: 0,
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + token },
  fileList: [],
});

function handleBeforeUpload() {
  upload.isUploading = true;
}

function handleFileUploadProgress({ percent }) {
  console.log('progress:', percent);
  upload.isUploading = true;
}

function handleFileSuccess({ event }) {
  const result = JSON.parse(event.currentTarget.response);
  console.log('upload success:', result);
  upload.isUploading = false;
  if (result.code === 200) {
    handleClose(true);

    dialog.success({
      title: '导入结果',
      content: () => (
        <div class="overflow-auto" style="max-height: 300px">
          <NText v-html={result.msg} />
        </div>
      ),
      positiveText: '确定',
    });
  }
}

function handleClose(needRefresh = false) {
  upload.fileList = [];
  emits('close', { needRefresh });
}

function handleChange(file) {
  upload.fileList = [file.file];
}

function submitFileForm() {
  uploadRef.value.submit();
}

function importTemplate() {
  download('/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
}
</script>

<style lang="less" scoped></style>
